/*
 *英才会硕信息科技有限公司拥有本软件的版权，拥有本软件版权2025   并保留所有权利。
 *Copyright 2021,YCHS Information&Science Technology Co.,Ltd,
 *All rights reserved.
 */
package com.ychs.lawyerback01.service.imp;

import com.ychs.lawyerback01.common.ResultCode;
import com.ychs.lawyerback01.dto.RoleOptDTO;
import com.ychs.lawyerback01.dto.RoleQueryDTO;
import com.ychs.lawyerback01.exception.BussinessException;
import com.ychs.lawyerback01.mapper.RoleMapper;
import com.ychs.lawyerback01.pojo.RoleEntity;
import com.ychs.lawyerback01.service.RoleService;
import com.ychs.lawyerback01.util.JwtUtils;
import com.ychs.lawyerback01.vo.RoleQueryVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuehongjin
 * @version 1.0
 * @date 2025/8/22
 */
@Service
public class RoleServiceImp implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Map<String, Object> getRolesByCondition(RoleQueryDTO roleQueryDTO) {
        List<RoleQueryVo> roles = roleMapper.getRolesByCondition(roleQueryDTO);
        int total = roleMapper.getCountByCondition(roleQueryDTO);

        Map<String, Object> map = new HashMap<>();
        map.put("list", roles);
        map.put("total", total);
        return map;
    }

    @Override
    @Transactional
    public int addRole(RoleOptDTO roleOptDTO) {
        // 检查权限字符是否已存在
        RoleEntity existingRole = roleMapper.getRoleByRoleKey(roleOptDTO.getRoleKey());
        if (existingRole != null) {
            throw new BussinessException(ResultCode.WORD_EXIST);
        }

        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(roleOptDTO, roleEntity);

        // 从JWT token中获取当前用户ID
        Long currentUserId = getCurrentUserIdFromToken();
        roleEntity.setCreateBy(currentUserId);

        return roleMapper.addRole(roleEntity);
    }

    @Override
    @Transactional
    public int editRole(RoleOptDTO roleOptDTO) {
        // 检查权限字符是否已存在（排除当前角色）
        RoleEntity existingRole = roleMapper.getRoleByRoleKey(roleOptDTO.getRoleKey());
        if (existingRole != null && !existingRole.getRoleId().equals(roleOptDTO.getRoleId())) {
            throw new BussinessException(ResultCode.WORD_EXIST);
        }

        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(roleOptDTO, roleEntity);

        // 从JWT token中获取当前用户ID
        Long currentUserId = getCurrentUserIdFromToken();
        roleEntity.setUpdateBy(currentUserId);

        return roleMapper.editRole(roleEntity);
    }

    @Override
    @Transactional
    public int deleteRoles(List<Long> roleIds) {
        // 检查角色是否被用户使用
        // 这里可以添加业务逻辑检查角色是否被使用

        return roleMapper.deleteRoles(roleIds);
    }

    /**
     * 从JWT token中获取当前用户ID
     */
    private Long getCurrentUserIdFromToken() {
        String token = extractTokenFromRequest();
        if (token != null && jwtUtils.validateToken(token)) {
            try {
                String userIdStr = jwtUtils.extractId(token);
                return Long.parseLong(userIdStr);
            } catch (Exception e) {
                // 如果无法从token中获取用户ID，返回默认值
                return getDefaultUserId();
            }
        }
        return getDefaultUserId();
    }

    /**
     * 从请求头中提取token
     */
    private String extractTokenFromRequest() {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }

    /**
     * 获取默认用户ID（用于测试或开发环境）
     */
    private Long getDefaultUserId() {
        // 这里可以根据需要返回一个默认的用户ID
        // 在生产环境中，您可能希望抛出异常而不是返回默认值
        return 1L;
    }
}